{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "956e6ddc-aa66-4539-8ecc-419ef257789c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1010\n"
     ]
    }
   ],
   "source": [
    "def convert(X):\n",
    "    import re\n",
    "    result=\"\"\n",
    "    num=int(X)\n",
    "    if num<0:\n",
    "        numpo=abs(num)\n",
    "        while numpo!=0:\n",
    "            result=str(numpo%2)+result\n",
    "            numpo=numpo//2\n",
    "        result=''.join(\"0\" if i==\"1\" else \"1\" for i in result)\n",
    "        #for i in range (0,len(result)):\n",
    "            #if result[i] == \"1\":\n",
    "                #result=result[:i]+\"0\"+result[i+1:]\n",
    "            #else:\n",
    "                #result=result[:i]+\"1\"+result[i+1:]\n",
    "        #不够优雅的写法（运行速度慢）\n",
    "    elif num>0:\n",
    "        while num!=0:\n",
    "            result=str(num%2)+result\n",
    "            num=num//2\n",
    "    else:\n",
    "        result=\"0000\"\n",
    "    if len(result)%4!=0:\n",
    "        result=\"0\"*(len(result)%4)+result\n",
    "    result=re.sub(r'^0{4}','',result)\n",
    "    print(result)\n",
    "convert(\"10\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9400e41c-9422-4164-ae20-7a99c1ea6c3d",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
